import React, { useState, useEffect, useMemo } from 'react'
import {
  Button,
  DatePicker,
  Form,
  Space,
  Modal,
  Drawer,
  Checkbox,
  Typography,
  Select
} from 'antd'
import { equipmentData } from '&/api/electricity'
import {
  SearchOutlined,
  FilterOutlined,
  DownloadOutlined
} from '@ant-design/icons'
import { FilterContainer } from '@/appComponents/Filter'
import dayjs from 'dayjs'
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'
import './index.scss'

const Filter = ({
  onQuery,
  paramsData,
  setParamsData,
  columns,
  onConfirm,
  onDataLoaded,
  dynamicColumns,
  onDownloadExcel,
  setLoading
}) => {
  const [formatData, setFormatData] = useState('YYYY-MM-DD HH:mm:00')
  const minuteStep15Time = useMemo(
    () => dayjs().subtract(dayjs().minute() % 15, 'minute'),
    []
  )
  const [isDrawerVisible, setIsDrawerVisible] = useState(false)
  const [selectedColumns, setSelectedColumns] = useState([])
  const [draggableColumns, setDraggableColumns] = useState(
    columns.map((col) => ({
      ...col,
      selected: false // 新增属性以追踪列是否被选中
    }))
  )

  useEffect(() => {
    if (Array.isArray(dynamicColumns)) {
      setDraggableColumns(
        dynamicColumns.map((col) => ({
          ...col,
          selected: selectedColumns.includes(col.dataIndex)
        }))
      )
    }
  }, [dynamicColumns, selectedColumns])

  const onDragEnd = (result) => {
    if (!result.destination) {
      return
    }
    const items = reorder(
      draggableColumns,
      result.source.index,
      result.destination.index
    )
    setDraggableColumns(items)
  }

  useEffect(() => {
    handleSearchAndPreview()
  }, [])

  const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list)
    const [removed] = result.splice(startIndex, 1)
    result.splice(endIndex, 0, removed)
    return result
  }

  const confirmAndPreview = () => {
    if (selectedColumns.length === 0) {
      // 如果没有选中任何列，显示提示消息
      Modal.warning({
        title: '提示',
        content: '请您选择需要展示的数据列。'
      })
    } else {
      const selectedOrderedColumns = draggableColumns.filter((col) =>
        selectedColumns.includes(col.key)
      )
      onConfirm(selectedOrderedColumns)
      onCloseDrawer()
    }
  }

  const showDrawer = () => {
    setDraggableColumns(
      dynamicColumns.map((col) => ({
        ...col,
        selected: selectedColumns.includes(col.dataIndex)
      }))
    )
    setIsDrawerVisible(true)
  }

  const onCloseDrawer = () => {
    setIsDrawerVisible(false)
  }

  const onCheckboxChange = (e, itemKey) => {
    setSelectedColumns((prevSelectedColumns) => {
      if (e.target.checked) {
        // 如果复选框被选中，则添加该 key
        return [...prevSelectedColumns, itemKey]
      } else {
        // 如果复选框未被选中，则移除该 key
        return prevSelectedColumns.filter((key) => key !== itemKey)
      }
    })
  }

  const handleSearchAndPreview = () => {
    setLoading(true)
    const params = {
      start_time: paramsData.start_time,
      end_time: paramsData.end_time,
      time_type: paramsData.time_type
    }
    equipmentData(params).then((res) => {
      setLoading(false)
      onDataLoaded(res)
    })
  }

  const onQueryChange = (v) => {
    const st = v[0].format('YYYY-MM-DD 00:00:00')
    const et = v[1].format('YYYY-MM-DD 00:00:00')
    setParamsData((state) => {
      state.start_time = st
      state.end_time = et
      return {
        ...state
      }
    })
  }

  const timeType = (v) => {
    setParamsData((state) => ({ ...state, time_type: v }))
    if ([1, 2].includes(v)) {
      setFormatData('YYYY-MM-DD HH:mm:00')
      setParamsData((state) => {
        state.start_time = dayjs(minuteStep15Time)
          .subtract(6, 'h')
          .format('YYYY-MM-DD HH:mm:00')
        state.end_time = dayjs(minuteStep15Time).format('YYYY-MM-DD HH:mm:00')
        return {
          ...state
        }
      })
    } else {
      setFormatData('YYYY-MM-DD')
      setParamsData((state) => {
        state.start_time = dayjs()
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:00:00')
        state.end_time = dayjs().format('YYYY-MM-DD HH:00:00')
        return {
          ...state
        }
      })
    }
  }

  return (
    <FilterContainer>
      <Form style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Form.Item label="时间粒度" style={{ width: '200px' }}>
          <Select
            value={paramsData.time_type}
            allowClear
            placeholder={`请选择`}
            onChange={(v) => timeType(v)}
          >
            <Select.Option value={1} key="1">
              15分钟
            </Select.Option>
            <Select.Option value={2} key="2">
              小时
            </Select.Option>
            <Select.Option value={3} key="3">
              日
            </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="日期">
          <DatePicker.RangePicker
            showNow
            format={formatData}
            showTime={formatData}
            defaultValue={[
              dayjs(paramsData.start_time),
              dayjs(paramsData.end_time)
            ]}
            value={[dayjs(paramsData.start_time), dayjs(paramsData.end_time)]}
            onChange={(v) => {
              onQueryChange(v)
            }}
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearchAndPreview}
            >
              查询并预览
            </Button>
            <Button
              icon={<DownloadOutlined />}
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => {
                onDownloadExcel()
              }}
            >
              导出
            </Button>
            <Button
              type="primary"
              icon={<FilterOutlined />}
              onClick={showDrawer}
            >
              筛选
            </Button>
          </Space>
          <Drawer
            title="筛选"
            placement="right"
            closable={true}
            onClose={onCloseDrawer}
            open={isDrawerVisible}
            width={300}
            footer={
              <div
                style={{
                  textAlign: 'right'
                }}
              >
                <Button onClick={confirmAndPreview} type="primary">
                  确认并预览
                </Button>
              </div>
            }
          >
            <Typography.Text type="secondary">
              提示:拖拽可以改变表头排列顺序。
            </Typography.Text>
            <DragDropContext onDragEnd={onDragEnd}>
              <Droppable droppableId="droppable">
                {(provided, snapshot) => (
                  <div ref={provided.innerRef} {...provided.droppableProps}>
                    {draggableColumns.map((item, index) => (
                      <Draggable
                        key={item.key}
                        draggableId={item.key}
                        index={index}
                      >
                        {(provided, snapshot) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                            style={{
                              ...provided.draggableProps.style,
                              marginBottom: '8px',
                              backgroundColor: snapshot.isDragging
                                ? '#f0f0f0'
                                : '#fff',
                              display: 'flex',
                              alignItems: 'center',
                              padding: '8px'
                            }}
                          >
                            <Checkbox
                              checked={selectedColumns.includes(item.key)}
                              onChange={(e) => onCheckboxChange(e, item.key)}
                            >
                              {item.title}
                            </Checkbox>
                          </div>
                        )}
                      </Draggable>
                    ))}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </DragDropContext>
          </Drawer>
        </Form.Item>
      </Form>
    </FilterContainer>
  )
}

export default Filter
